<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cates = DB::table('cates')->get();
        $cates = $this -> findSubTree($cates,0,0);
        return view('cate.category',['cates'=>$cates]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
//         $cates = DB::table('cates')->get();
//         $cates = $this -> findSubTree($cates,0,0);
        return view('cate.categoryAdd');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {       
        $data=['pid'=>$request->pid,'name'=>$request->name];
        $res = DB::table('cates')->insert($data);
        return redirect()->back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


//     protected function findSubTree($cates,$id=0,$lev=1)
//     {
//         $subtree = [];
//         foreach($cates as $v){
//             if($v -> pid == $id){
//                 $v -> lev = $lev;
//                 $subtree[] = $v;
//                 $subtree = array_merge($subtree,$this->findSubTree($cates,$v->id,$lev+1));
//             }
//         }
//         return $subtree;
//     }
    protected function findSubTree($cates,$id=0,$lev=1)
    {
        $subtree = [];
        foreach($cates as $v){
            if($v -> pid == $id){
                $v -> lev = $lev;
                $subtree[] = $v;
                $subtree = array_merge($subtree,$this->findSubTree($cates,$v->id,$lev+1));
            }
        }
        return $subtree;
    }
}
